<template>
  <div class="table-content">
    <div class="table-tools" v-if="tool">
      <div class="table-search">
        <slot name="easySearch" v-if="easy">
          <Form inline>
            <FormItem>
              <Input
                search
                enter-button
                :placeholder="placeholder"
                @on-search="easySearch"
                v-width="300"
                v-model="keys"
              />
            </FormItem>
          </Form>
        </slot>
        <a v-if="high" @click="modalSearch = true">
          <Icon type="md-search"></Icon>
          高级</a
        >
      </div>
      <div class="searchBack">
        <slot name="searchBack"></slot>
      </div>
      <div class="btns">
        <slot name="buttons"></slot>
        <Button
          v-if="cid && type == 'table'"
          @click="config = !config"
          shape="circle"
          title="设置"
        >
          <i class="iconfont iconlieshezhi"></i
        ></Button>
      </div>
    </div>
    <div class="table-main" ref="main">
      <Row v-if="type == 'card'" :gutter="40">
        <Col :span="span" v-for="(row, i) in list" :key="i">
          <slot name="card" :row="row">
            <span>{{ row.id }}</span>
          </slot>
        </Col>
        <Col v-if="list.length == 0" span="24" class="zan-wu">
          <h4>暂无数据</h4>
        </Col>
      </Row>
      <Table
        v-else
        :border="border"
        :columns="columnsNow"
        :data="list"
        :height="tableHeight"
        :draggable="draggable"
        :show-summary="showSummary"
        ref="table"
        class="tableCommon"
        @on-expand="expand"
        @on-drag-drop="onDragDrop"
        @on-selection-change="selectionChange"
        @on-select="onSelect"
        :summary-method="summaryMehod"
        @on-select-all="allChange"
        @on-sort-change="sortChange"
        @on-row-click="rowClick"
        :row-key="rowKey"
        stripe
      ></Table>
    </div>
    <div class="table-footer">
      <slot name="footer"></slot>
      <Page
        v-if="page"
        :total="search.total"
        :current="search.page"
        class="fr"
        show-total
        size="small"
        show-elevator
        show-sizer
        :page-size="search.pageSize"
        :page-size-opts="pageSizeOpts"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
      />
    </div>
    <Modal
      v-if="high"
      v-model="modalSearch"
      title="高级搜索"
      draggable
      width="800"
      ref="search"
    >
      <slot name="searchForm"></slot>
      <div slot="footer">
        <Button @click="modalSearch = false" style="margin-left: 20px"
          >取消</Button
        >
        <Button @click="complexSearch" type="primary" style="margin-left: 10px"
          >查询</Button
        >
      </div>
    </Modal>
    <Drawer
      title="列设置"
      v-if="cid"
      v-model="config"
      :scrollable="true"
      placement="left"
      :mask="false"
    >
      <div slot="header">
        列设置
        <a @click="undoConfig" class="ml50">
          <Icon type="md-refresh" title="恢复初始设置" />
        </a>
      </div>
      <ul class="table-columns">
        <li
          v-for="(li, index) in columnsCur"
          :key="index"
          v-dragging="{ item: li, list: columnsCur, group: 'li' }"
        >
          <label @click="columnChange(li, index)" :class="{ dis: li.hide }">
            <Icon
              :type="li.hide ? 'md-eye-off' : 'md-eye'"
              size="16"
              class="mr10"
            />
            <span>{{ li.title }}</span>
          </label>
          <Icon type="ios-move" class="move" size="18" />
        </li>
      </ul>
    </Drawer>
    <FooterToolbar v-if="batch" v-show="footerToolbar">
      <span class="ib fc-info">已选{{ selectItems.length }}项</span>
      <slot name="batch"></slot>
      <Button @click="cancelBatch">取消</Button>
    </FooterToolbar>
  </div>
</template>

<script>
import ColumnSlot from "./components/columnSolt";
export default {
  name: "DataGrid",
  components: {
    ColumnSlot,
  },
  data() {
    return {
      keys: "", //
      selectItems: [], //多选项目
      footerToolbar: false,
      modalSearch: false,
      search: {
        pageIndex: 1,
        pageSize: 20,
        sortBy: this.conditions.sortBy ? this.conditions.sortBy : "id",
        isDesc: true,
        conditions: [],
      },
      pageSizeOpts: [20, 50, 100],
      tableHeight: 0,
      firstY: 0,
      config: false,
      list: [],
      columnsCur: [],
      configLoad: false,
      userConfig: null, //用户页面配置信息。,
      treeData: [], //物料数据
      codeRuleData: [], //物料编码
      routingHeaderData: [], //工艺规程
      allUser: [], //所有user
    };
  },
  props: {
    cid: {
      //组件配置信息唯一编码
      type: String,
    },
    border: {
      //是否显示边框
      type: Boolean,
      default: true,
    },
    showSummary: {
      //是否显示合计
      type: Boolean,
      default: false,
    },
    summaryMehod: {
      //是否显示合计
      type: Function,
    },
    batch: {
      //是否批量操作
      type: Boolean,
      default: true,
    },
    format: {
      type: Function,
      default: null,
    },
    lazy: {
      //懒加载设置，设置为真时候，默认不加载数据。
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请输入关键字",
    },
    height: {
      type: Number,
      default: 0,
    },
    tool: {
      //是否显示工具栏
      type: Boolean,
      default: true,
    },
    easy: {
      //是否显示简单搜索
      type: Boolean,
      default: true,
    },
    high: {
      //是否显示高级搜索
      type: Boolean,
      default: false,
    },
    draggable: {
      //是否可以拖拽
      type: Boolean,
      default: false,
    },
    page: {
      //是否分页
      type: Boolean,
      default: true,
    },
    data: {
      // 当作table使用，直接显示数据
      type: Array,
      default: function() {
        return [];
      },
    },
    columns: {
      //要显示的字段,不传自动根据数据获取
      type: Array,
      // default: [],
    },
    action: {
      //接口地址
      type: [String, Object],
    },
    conditions: {
      //查询条件
      type: Object,
      default: function() {
        return {
          keys: {
            op: "name",
            value: "",
            default: true,
          },
        };
      },
    },
    type: {
      type: String,
      default: "table",
      validator: function(value) {
        // 这个值必须匹配下列字符串中的一个
        return ["table", "card", "list"].indexOf(value) !== -1;
      },
    },
    span: {
      //栅格数
      type: Number,
      default: 24,
    },
    //table控件children子数据控制功能
    rowKey: {
      type: [String, Number],
    },
    gutter: {
      //间距
      type: Number,
      default: 40,
    },
    exportTitle: {
      type: String,
      default: "",
    },
  },
  created() {
    if (this.data && this.data.length > 0) {
      this.list = this.data;
      this.autoColumns();
      return;
    }
  },
  mounted() {
    this.initColumns();
    this.keys = "";
    this.intY();
    if (this.lazy == true) {
      return;
    }
    //debugger;
    if (
      this.$store.state.userInfo &&
      this.$store.state.userInfo.userId > 0 &&
      this.cid
    ) {
      this.loadUserConfig();
    } else {
      this.easySearch();
    }
    if (this.height === 0) {
      this.$nextTick(() => {
        this.tableHeight = this.$refs.main.offsetHeight;
        if (this.tableHeight < 300) {
          this.tableHeight =
            window.screen.availHeight - this.$refs.main.offsetTop - 200;
        }
        window.onresize = () => {
          ///浏览器窗口大小变化
          return (() => {
            if (this.$refs.main && this.$refs.main.offsetHeight) {
              this.tableHeight = this.$refs.main.offsetHeight;
              if (this.tableHeight < 300) {
                this.tableHeight =
                  window.screen.availHeight - this.$refs.main.offsetTop - 150;
              }
            }
          })();
        };
      });
    } else {
      this.tableHeight = this.height;
    }
    //注册拖拽事件。
    this.$dragging.$on("dragend", (e) => {
      this.saveUserconfig();
    });
  },

  methods: {
    rowClick(value, index) {
      this.$emit("on-row-click", value, index);
    },
    initColumns() {
      if (!this.columns) {
        return;
      }
      var items = this.$u.clone(this.columns).map((u) => {
        if (u.slot) {
          u.slotName = u.slot;
          delete u.slot;
        }
        return u;
      });
      items.forEach((u) => {
        if (!u.hide) {
          u.hide = false;
        }
        u.minWidth = 120;
        if (u.slotName) {
          u.render = (h, ctx) => {
            return this.$scopedSlots[ctx.column.slotName]({
              row: ctx.row,
              column: ctx.column,
              index: ctx.index,
            });
          };
        }
        if (u.code) {
          u.render = (h, params) => {
            let values = u.key;
            let type = "text";
            if (u.category) {
              type = u.category;
            }
            return h("state", {
              props: {
                code: u.code,
                type: type,
                value: params.row[values] + "",
              },
            });
          };
        }
        if (u.type == "user") {
          u.render = (h, params) => {
            let values = u.key;
            if (params.row[values]) {
              return h("User", {
                props: {
                  value: params.row[values],
                },
              });
            }
          };
        }
        if (u.type == "users") {
          u.render = (h, params) => {
            let values = u.key;
            if (params.row[values]) {
              var users = params.row[values];
              return h(
                "div",
                users.map((u) => {
                  return h("User", {
                    class: "pr10",
                    props: {
                      value: u,
                    },
                  });
                })
              );
            }
          };
        }
        if (u.type == "workShopName") {
          u.render = (h, params) => {
            let values = u.key;
            if (params.row[values]) {
              return h("WorkShopName", {
                props: {
                  value: params.row[values],
                },
              });
            }
          };
        }
        if (u.type == "date" || u.type == "dateTime") {
          u.render = (h, params) => {
            let values = u.key;
            return h("DtSpan", {
              props: {
                type: u.type,
                value: params.row[values],
              },
            });
          };
        }
      });
      this.columnsCur = items;
    },
    //根据数据自动加载列
    autoColumns() {
      if (!this.columns && this.list[0]) {
        this.columnsCur = Object.keys(this.list[0]).map((u) => {
          return {
            key: u,
            title: u,
            hide: false,
          };
        });
      }
    },
    //数据加载
    load() {
      if (this.action) {
        let ret = this.$u.type(this.action);
        if (ret === "string") {
          this.$api.post(this.action, this.search).then((r) => {
            if (this.format) {
              this.list = this.format(r.result.items);
            } else {
              this.list = r.result.items;
            }
            this.autoColumns();
            this.search.total = r.result.totalCount || r.result.count;
          });
        } else if (this.action.paged) {
          this.action.paged(this.search).then((r) => {
            if (this.format) {
              this.list = this.format(r.result.items);
            } else {
              this.list = r.result.items;
            }
            this.autoColumns();
            this.search.total = r.result.totalCount || r.result.count;
          });
        }
      }
    },
    easySearch() {
      if (
        this.conditions &&
        this.conditions.keys &&
        this.conditions.keys.default
      ) {
        //判断没有传入条件的用默认的查询
        this.conditions.keys.value = this.keys;
      }
      this.reload(this.conditions);
    },
    complexSearch() {
      var search = this.$refs.search.$children.filter((u) => {
        return u.condition;
      });
      if (search) {
        var conditions = search[0].condition;
        this.reload(conditions);
      }
    },
    reload(conditions) {
      var where = this.$u.conditions(conditions);
      this.search.pageIndex = 1;
      this.search.conditions = where;
      this.load();
    },
    columnInit() {
      if (this.userConfig) {
        var curColumns = [];
        var config = JSON.parse(this.userConfig.content);
        if (config.length == this.columnsCur.length) {
          config.map((u) => {
            var item = this.columnsCur.filter((c) => {
              return c.key == u.key;
            });
            if (item[0]) {
              item[0].hide = u.hide;
              curColumns.push(item[0]);
            }
          });
          this.columnsCur = curColumns;
        }
      }
    },
    loadUserConfig() {
      var query = {
        conditions: [
          {
            fieldName: "creatorUserId",
            fieldValue: this.$store.state.userInfo.userId,
            conditionalType: "Equal",
          },
          {
            fieldName: "component",
            fieldValue: "DataGrid",
            conditionalType: "Equal",
          },
          {
            fieldName: "page",
            fieldValue: this.cid,
            conditionalType: "Equal",
          },
        ],
        pageSize: 1,
      };
      this.$api.post(`${window.systemUrl}/config/list`, query).then((r) => {
        if (r.success) {
          if (r.result.length == 1) {
            this.userConfig = r.result[0];
            this.columnInit();
          }
          if (!this.configLoad) {
            this.easySearch();
          }
          this.configLoad = true;
        }
      });
    },
    saveUserconfig() {
      let url = `${window.systemUrl}/config/update`;
      var content = [];
      this.columnsCur.map((u) => {
        content.push({
          key: u.key,
          hide: u.hide,
        });
      });
      if (!this.userConfig) {
        url = `${window.systemUrl}/config/create`;
        var data = {
          page: this.cid,
          component: "DataGrid",
          key: this.$u.guid(),
          content: JSON.stringify(content),
        };
        this.$api.post(url, data).then((r) => {
          this.loadUserConfig();
        });
      } else {
        this.userConfig.content = JSON.stringify(content);
        this.$api.post(url, this.userConfig);
      }
    },
    undoConfig() {
      //列设置恢复初始化
      this.columnsCur = this.$u.clone(this.columns);
      this.saveUserconfig();
    },
    //拖拽
    onDragDrop(a, b) {
      this.$emit("on-drag-drop", a, b);
    },
    //展开
    expand(row, status) {
      this.$emit("on-expand", row, status);
    },

    //排序
    sortChange(column, key, order) {
      this.search.sortBy = key;
      this.search.isDesc = order == "desc";
      this.search.pageIndex = 1;
      this.load();
    },
    /// 分页变化
    pageChange(page) {
      this.search.page = page;
      this.search.pageIndex = page;
      this.load();
    },
    pageSizeChange(size) {
      this.search.pageSize = size;
      this.search.pageIndex = 1;
      this.load();
    },
    columnChange(item, i) {
      item.hide = !item.hide ? true : false;
      this.$set(this.columnsCur, item, i);
      this.saveUserconfig();
    },
    selectionChange(items) {
      this.$emit("on-selection-change", items);
      this.selectItems = items;
      this.footerToolbar = items.length > 0;
    },
    onSelect(rows, row) {
      this.$emit("on-change", rows, row);
    },
    allChange(items) {
      this.$emit("all-change", items);
    },
    intY() {
      if (this.$refs.table != undefined) {
        this.firstY = this.$refs.table.$el.getBoundingClientRect().top;
      }
    },
    selectAll(status) {
      this.$refs.table.selectAll(status);
    },
    //批量取消
    cancelBatch() {
      this.footerToolbar = false;
      this.$refs.table.selectAll(false);
    },
  },
  computed: {
    columnsNow() {
      var cols = this.columnsCur.filter((u) => {
        return !u.hide;
      });
      return cols;
    },
  },
  watch: {
    data() {
      this.list = this.data;
      this.autoColumns();
    },
    height() {
      this.tableHeight = this.height;
    },
    columns() {
      this.initColumns();
    },
  },
};
</script>
